繁体   English   中英

可变参数模板参数推导/替换失败,元编程

[英]Variadic template argument deduction/substitution failed, metaprogramming

我试图创建一个递归模板函数,但是我不断收到错误:

没有匹配的函数来调用meuPrint(int&,Separator&,string&)

同时还收到:

候选:模板字符串meuPrint(U ...,Separator&,string&)。

struct Separator {};    

template<class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text )
{//end
    char buffer[200];
    sprintf( buffer , text.c_str() , b... );
    return buffer;
}
template<class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , string value , T ...a )
{//string
    return meuPrint( b... , to_lower( value ) , placeholder , text , a... );
}

template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )
{//middle
    return meuPrint( b... , value , placeholder , text , a... );
}

template<class ...T>
string meuPrint( std::string _text , T ...a )
{//start
    Separator placeholder;
    return meuPrint( placeholder , _text , a... );
}

int main( int n , char** args )
{
    string o = meuPrint(  string( "hello %i world" )  ,  8 );
    std::cout << o << std::endl;
    return 0;
}

这里的目标不一定是小写参数,而是测试概念。 我不明白为什么编译器在随后告诉我一些有效的候选者时总是不断推论失败。

这样的事情行不通

template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )

经验法则:您只能有一组参数,这些参数必须位于参数列表的末尾。

因此,您可以合理地编写(并且编译器可以推断出)类似

template <typename V, typename ... T>
string meuPrint(V value, T ... a)

但是以下将失败

template <typename V, typename ... T>
string meuPrint(T ... a, V value)

两包参数,如下所示:

template <typename ... U, typename ... T>
string meuPrint(U ... u, T ... t)

不能推导出(包u和包t之间的边界在哪里?)。

如果有两包参数,则必须使用std::tuple类的参数来收集它们。 就像是

template <typename ... U, typename ... T>
string meuPrint(std::tuple<U ...> u, std::tuple<T ...> t)

但是可变参数元组的使用可能会有些困难。

离题建议:您正在使用C ++ 11;您正在使用C ++ 11。 而不是旧的C。丢弃sprintf()并使用C ++流设施。

在流中使用可变参数很简单(您可以忽略格式字符串)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM