c++ - 强制编译器只接受编译时参数( float )

标签 c++ templates c++11

我可以强制编译器只接受 constexpr 或函数的非变量输入吗?

我正在寻找只允许编译时值的函数。使用模板或任何其他方法。

Here ,有一个 int 模板的工作示例。 double 的问题在于它们不能用作模板参数。

#include <iostream>

template <double x>
void show_x()
{
    std::cout<<"x is always "<<x<<" in the entire program."<<std::endl;
}

int main()
{
    show_x<10.0>();
    return 0;
}

error: ‘double’ is not a valid type for a template non-type parameter


更新

对于那些将这个问题标记为重复的人,我不得不说:

我问问题

How to solve problem A?

Solution B does not work for problem A, I need another solution

然后你将我链接到为什么解决方案 B 不起作用。

这完全不合逻辑。

最佳答案

这里有两种方式:

更新:

有关用户规避的问题已得到解决。现在,X::value() 在使用之前由函数体内的 constexpr 变量获取。如果没有名为 value()constexpr 方法,现在无法传递 X

#include <iostream>


  struct always_10
  {
    constexpr static double value() { return 10.0; }
  };

template <class X>
void show_x()
{
  constexpr auto x = X::value();
  std::cout<<"x is always "<< x <<" in the entire program."<<std::endl;
}

template<class X>
void show_x(X x_)
{
  constexpr auto x = x_.value();
  std::cout<<"x is always "<< x <<" in the entire program."<<std::endl;
}

int main()
{
    show_x<always_10>();
    show_x(always_10());
    return 0;
}

关于c++ - 强制编译器只接受编译时参数( float ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39433759/

相关文章:

c++ - 如果相似元素已存在,则从 std::list 中移除元素

c++ - GCC中的lambda函数有多快

类似类的 C++ 类模板

c++ - 如何打破 for 循环并转换整数?

c++ - Windows 获取卷上所有文件的大小列表

c++ - 使用模板时:错误:没有匹配的构造函数用于初始化

c++ - 模板-无法将函数定义与现有声明c++匹配

c++ - 顺时针旋转M*N矩阵90度,C++

c++ - 如何显示动画情节?

c++ - 为什么拷贝构造函数不需要检查输入对象是否指向自己?