gpt4 book ai didi

c++ - 可变参数成员函数模板是否可以有两个参数的基本情况?

转载 作者:行者123 更新时间:2023-11-30 02:37:09 24 4
gpt4 key购买 nike

考虑以下代码:

class Foo {
public:
template<typename X, typename T, typename ... Args> static void f( );
//template<typename X, typename T> static void f( );
template<typename X> static void f( );
};

template<typename X> void Foo::f( ) {
cout << "Swallowed the last argument." << endl;
}

/*
template<typename X, typename T> void Foo::f( ) {
cout << "Swallowed last two arguments." << endl;
}
*/

template<typename X, typename T, typename ... Args> void Foo::f( ) {
cout << sizeof (T ) << endl;
Foo::f <X, Args...>( );
}


...
Foo::f<void*, int, double, long>( );
...

这工作正常,输出是:

4
8
8
Swallowed the last argument.

但是在我正在处理的特定问题中,我想在前一级停止递归,如注释掉的代码所示。当这些行没有被注释掉时,我得到错误(gcc 4.8.3):

g++ -Wall -std=c++1y -march=native -fmessage-length=0 -Wno-multichar   -g  -c -o obj/OneOff/OneOff.o OneOff/OneOff.cpp
OneOff/OneOff.cpp: In instantiation of ‘static void Foo::f() [with X = void*; T = double; Args = {long int}]’:
OneOff/OneOff.cpp:132:23: required from ‘static void Foo::f() [with X = void*; T = int; Args = {double, long int}]’
OneOff/OneOff.cpp:137:36: required from here
OneOff/OneOff.cpp:132:23: error: call of overloaded ‘f()’ is ambiguous
Foo::f <X, Args...>( );
^
OneOff/OneOff.cpp:132:23: note: candidates are:
OneOff/OneOff.cpp:130:58: note: static void Foo::f() [with X = void*; T = long int; Args = {}]
template<typename X, typename T, typename ... Args> void Foo::f( ) {
^
OneOff/OneOff.cpp:125:39: note: static void Foo::f() [with X = void*; T = long int]
template<typename X, typename T> void Foo::f( ) {
^
gmake: *** [obj/OneOff/OneOff.o] Error 1

是否有可能以某种方式告诉编译器两个参数版本是特化/基本情况。例如。使用像 < .. , typename Args = {}>?

这样的东西

我发现的一种替代方法是将 f() 更改为:

template<typename X, typename T, typename ... Args> void Foo::f( ) {
cout << sizeof (T ) << endl;
if ( sizeof ...( Args ) > 1 ) {
Foo::f <X, Args...>( );
} else {
cout << "Swallowed last two arguments." << endl;
}
}

这给出了期望的结果,并且可能一旦生成了个体变体,“if ... elses”就会与基本情况一起被优化掉。然而,它看起来有点像 hack。

最佳答案

选项#1

让可变版本至少采用三个固定类型模板参数:

template <typename X, typename T, typename V, typename... Args>
static void f();

// ...

template <typename X, typename T, typename V, typename... Args>
void Foo::f()
{
Foo::f<X, V, Args...>( );
}

DEMO 1

选项#2

如果包的大小等于 0,则使用 SFINAE 禁用可变版本:

#include <type_traits>

template <typename X, typename T, typename... Args>
static auto f()
-> typename std::enable_if<(sizeof...(Args) > 0)>::type;

//...

template <typename X, typename T, typename... Args>
auto Foo::f()
-> typename std::enable_if<(sizeof...(Args) > 0)>::type
{
Foo::f<X, Args...>( );
}

DEMO 2

关于c++ - 可变参数成员函数模板是否可以有两个参数的基本情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31967666/

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