Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A curious case with references and static class members

Take the following piece of code:

#include <type_traits>
#include <iostream>

template <class T>
void print(T &&t){
    std::cout << t << std::endl;
}

template<class T, T val>
struct Foo{
    static constexpr T value = val;
};

int main(){
    print(Foo<int, 123>::value);
}

It refuses to compile under Clang 3.3 and GCC 4.8.1 ("undefined reference to Foo<int, 123>::value"), which puzzles me because Foo does exactly the same as std::integral_constant, and the same code runs fine with integral_constant. It also fails with plain lvalue reference in the print function. Any explanation regarding this behaviour?

The issue is also present with this quite minimal example:

template<class T>
struct Bar{
    static const bool value = true;
};
like image 552
András Kovács Avatar asked Jun 30 '13 16:06

András Kovács


1 Answers

As the compiler says, there is no reference to the static variable, you must add

template<class T, T val>
constexpr T Foo<T, val>::value;

after the definition of the class Foo

like image 176
Stefano Falasca Avatar answered Sep 27 '22 18:09

Stefano Falasca