constexpr kiedy używać

0

Kiedy używać

constexpr

a kiedy const

 ?
1

constexpr mówi, że zmienna jest znana podczas kompilacji (oprócz tego, że jest to stała). Standard języka określa to jako constant expression. const mówi tylko, że wartość nie będzie zmieniana. Jej definicja może być zarówno w runtime jak i w compile-time. W standardzie po prostu constant.
constexpr nie jest jednak jedynym sposobem na zdefiniowanie constant expression:

template <int a>
class foo { };

int main () {
    const int value = 42;
    foo<value> fooo;
    static_assert(value == 42);
    constexpr int c_value = value;
    int array[value];
}

W kodzie powyżej zmienna value jest dokładnie tym samym co constexpr - const znany w compile-time zaincjalizowany integer literal. Ale wyobraź sobie taki kod:

template <int a>
class foo { };

int give () {
    int a;
    std::cin >> a;
    return a;
}

int main () {
    const int value = give();
    foo<value> fooo; // nope
    static_assert(value == 42); // nope
    constexpr int c_value = value; // nope
    int array[value]; // nope
}

Tutaj też mamy const, jednak nie jest to constant expression.

0

Dodam do tego co jest wyżej, że funkcja i konstruktor mogą być constexpr, co oznacza, że mogą być wykonane w czasie kompilacji.
Nawet można się bawić ze stringami:

#include <iostream>
using namespace std;

template <int a>
class foo 
{
public:
	int n;
	constexpr foo() : n(a) { }
};

template <int a>
class foo2
{
public:
	static constexpr int n = a;	
};

template <size_t N>
constexpr int simple_checksum(const char (&str)[N], int index = 0)
{
	return (str[index] ? str[index] + simple_checksum(str, index+1) : 0);
}

int main() {
	foo<simple_checksum("ala ma kota")> a;
	cout << "checksum: " << a.n << endl;
	cout << "checksum 2: " << foo2<simple_checksum("ala ma kota")>::n << endl;
	return 0;
}

http://ideone.com/m2fGU5

Dodam tylko, że w Visual Studio 2015 nadal nie można stosować constexpr w zmiennych. Jedynie funkcje i konstruktory mogą być constexpr.

1 użytkowników online, w tym zalogowanych: 0, gości: 1