当我尝试float用作模板参数时,编译器会为此代码而烦恼,同时int工作正常.
是因为我不能float用作模板参数吗?
#include<iostream>
using namespace std;
template <class T, T defaultValue>
class GenericClass
{
private:
T value;
public:
GenericClass()
{
value = defaultValue;
}
T returnVal()
{
return value;
}
};
int main()
{
GenericClass <int, 10> gcInteger;
GenericClass < float, 4.6f> gcFlaot;
cout << "\n sum of integer is "<<gcInteger.returnVal();
cout << "\n sum of float is "<<gcFlaot.returnVal();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:
main.cpp: In function `int main()':
main.cpp:25: error: `float' is not a …Run Code Online (Sandbox Code Playgroud) 考虑以下内联函数:
// Inline specifier version
#include<iostream>
#include<cstdlib>
inline int f(const int x);
inline int f(const int x)
{
return 2*x;
}
int main(int argc, char* argv[])
{
return f(std::atoi(argv[1]));
}
Run Code Online (Sandbox Code Playgroud)
和constexpr等效版本:
// Constexpr specifier version
#include<iostream>
#include<cstdlib>
constexpr int f(const int x);
constexpr int f(const int x)
{
return 2*x;
}
int main(int argc, char* argv[])
{
return f(std::atoi(argv[1]));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:说明constexpr符是否意味着说明inline符,如果一个非常量参数传递给一个constexpr函数,编译器将尝试inline该函数,就像说明inline符被放入其声明一样?
C++ 11标准能保证吗?
在C++ 11中,我们得到constexpr:
constexpr int foo (int x) {
return x + 1;
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用编译时错误foo的动态值进行调用x?也就是说,我想创建一个foo只能传递constexpr参数的东西.
给出以下代码:
constexpr int omg() { return 42; }
const int a = omg(); // NOT guaranteed to be evaluated at compile time
constexpr const int a = omg(); // guaranteed to be evaluated at compile time
Run Code Online (Sandbox Code Playgroud)
有没有办法强制在编译时评估某些东西而不将其分配给constexpr(或者在编译时上下文中,比如模板参数ot enum shenanigans)?
像这样的东西:
const int a = force_compute_at_compile_time(omg());
Run Code Online (Sandbox Code Playgroud)
也许这样的东西(不编译 - 我还没有太多进入constexpr):
template<typename T> constexpr T force_compute_at_compile_time(constexpr const T& a) { return a; }
Run Code Online (Sandbox Code Playgroud) 目前,我们有两个主要的编译时评估选项:模板元编程(通常使用模板结构和/或变量)和constexpr操作1。
template<int l, int r> struct sum_ { enum { value = l + r }; }; // With struct.
template<int l, int r> const int sum = sum_<l, r>::value; // With struct & var.
template<int l, int r> const int sub = l - r; // With var.
constexpr int mul(int l, int r) { return l * r; } // With constexpr.
Run Code Online (Sandbox Code Playgroud)
其中,我们保证可以在编译时对所有这四个值进行评估。
template<int> struct CompileTimeEvaluable {};
CompileTimeEvaluable<sum_<2, 2>::value> template_struct; // Valid.
CompileTimeEvaluable<sum<2, 2>> …Run Code Online (Sandbox Code Playgroud)