让我们来看一个简单的 SFINAE模板示例
#include <iostream>
template <typename T>
struct has_typedef_foobar {
// Types "yes" and "no" are guaranteed to have different sizes,
// specifically sizeof(yes) == 1 and sizeof(no) == 2.
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::foobar*);
template <typename>
static no& test(...);
// If the "sizeof" of the result of calling test<T>(0) would be equal to sizeof(yes),
// the first overload worked and T has a nested type named foobar.
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
struct foo {
typedef float foobar;
};
int main() {
std::cout << std::boolalpha;
std::cout << has_typedef_foobar<int>::value << std::endl;
std::cout << has_typedef_foobar<foo>::value << std::endl;
}
布尔值bool
没有被声明为constexpr
,但它仍然在编译时获得其值。那么constexpr
的用途是什么?为什么简单的静态变量会在编译时获得它们的值?如何判断哪些静态变量在编译时获得它们的值?
另外,如何判断哪些值将在编译时计算,哪些不会?使用constexpr
是否保证了编译时计算?如果不是,如何知道哪些会发生(编译时或运行时)?