C ++ 11 constexpr函数的参数在模板参数中传递 [英] C++11 constexpr function's argument passed in template argument

查看:199
本文介绍了C ++ 11 constexpr函数的参数在模板参数中传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个工具在几个星期前已经运作:

This used to work some weeks ago:

template <typename T, T t>
T            tfunc()
{
    return t + 10;
}

template <typename T>
constexpr T       func(T t)
{
    return tfunc<T, t>();
}

int main()
{
    std::cout << func(10) << std::endl;
    return 0;
}

但现在 g ++ -std = c ++ 0x 说:

main.cpp: In function ‘constexpr T func(T) [with T = int]’:
main.cpp:29:25:   instantiated from here
main.cpp:24:24: error: no matching function for call to ‘tfunc()’
main.cpp:24:24: note: candidate is:
main.cpp:16:14: note: template<class T, T t> T tfunc()
main.cpp:25:1: warning: control reaches end of non-void function [-Wreturn-type]

clang ++ -std = c ++ 11 说模板的参数 tfunc< T,t& )被忽略,因为无效。

clang++ -std=c++11 says that template's parameters of tfunc<T, t>() are ignored because invalid.

这是一个错误还是修复?

Is that a bug, or a fix ?

PS:

g ++ --version => g ++ 2 20120120(prerelease)

clang ++ --version => clang version 3.0(tags / RELEASE_30 / final)(3.0.1)

clang++ --version => clang version 3.0 (tags/RELEASE_30/final) (3.0.1)

推荐答案

参数 t 不是常量表达式。因此错误。还应该注意,它不能是常量表达式。

The parameter t is not a constant expression. Hence the error. It should be also noted that it cannot be a constant expression.

您可以传递常量表达式作为参数,但在函数内部,保存该值的对象(参数)不是常量表达式。

You can pass the constant expression as argument, but inside the function, the object (the parameter) which holds the value, is not a constant expression.

由于 t 不是常量表达式,因此不能用作模板参数:

Since t is not a constant expression, it cannot be used as template argument:

return tfunc<T, t>(); //the second argument must be a constant expression






也许你想要这样的东西:


Maybe, you want something like this:

template <typename T, T t>
T  tfunc()
{
    return t + 10;
}

template <typename T, T t>  //<---- t became template argument!
constexpr T  func()
{
    return tfunc<T, t>();
}

#define FUNC(a)  func<decltype(a),a>()

int main()
{
    std::cout << FUNC(10) << std::endl;
}

现在它应该可以工作:在线演示

Now it should work : online demo

这篇关于C ++ 11 constexpr函数的参数在模板参数中传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆