gpt4 book ai didi

c++ - 为什么下面的程序没有选择与第一个模板参数相同类型的参数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:12:27 25 4
gpt4 key购买 nike

我正在尝试编写一个函数 f<T>(args..)返回 T 类型的第一个参数.

下面的程序似乎总是选择第一个特化从而打印 97 ('a' 的 ASCII 码)。虽然第二个不需要转换 charint .有人可以解释这种行为吗?

我是 SFINAE 和元编程的新手。

  #include <iostream>
using namespace std;

template <typename T, typename ...Ts>
T f(T a, Ts... args) {
return a;
}

template <typename R, typename T, typename ...Ts>
R f(typename enable_if<!is_same<R, T>::value, T>::type a, Ts... args) {
return f<R>(args...);
}

int main() {
cout << f<int>('a', 12);
}

最佳答案

std::enable_if 的第二个模板参数应该是 R,这是您想要的。

以下应该有效

 template < typename R, typename T, typename ...Ts>
typename enable_if<!is_same<R, T>::value, R>::type f(T const& t, Ts&&... args)
// ^^^ ^^^^^^^^^^^
{
return f<R>(std::forward<Ts>(args)...); // forward the args further
}

关于c++ - 为什么下面的程序没有选择与第一个模板参数相同类型的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55775535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com