可变参数模板麻烦匹配const和非const std :: string [英] Variadic template trouble matching const and non-const std::string
问题描述
我在构建可变参数模板时遇到了麻烦,其中扩展功能正确地与非const和const std :: string
匹配.我有一个通用的匹配函数,在某些情况下会被调用.
I'm having trouble constructing a variadic template where the expansion functions properly match both a non-const and const std::string
. I have a generic matching function which is called instead in some cases.
我已将代码简化为以下示例.不是字符串的东西应该以泛型函数结束.作为字符串的内容应该在第二个函数处结束,该函数另外输出"STRING".
I've reduced the code to the below example. Things which aren't a string should end up at the generic function. Things which are a string should end up at the second function which additionally outputs "STRING".
#include <iostream>
#include <string>
template<typename X, typename T>
void extend_exception( X & ex, T&& value )
{
ex << value << std::endl;
}
template<typename X>
void extend_exception( X & ex, std::string && value )
{
ex << "STRING: " << value << std::endl;
}
template<typename X, typename TF, typename ... TR>
void extend_exception( X & ex, TF&& f, TR&& ... rest )
{
extend_exception( ex, std::forward<TF>(f) );
extend_exception( ex, std::forward<TR>(rest)... );
}
int main()
{
extend_exception( std::cout, std::string( "Happy" ) );
std::string var( "var" );
extend_exception( std::cout, var );
extend_exception( std::cout, var, std::string( "Combo" ), const_cast<std::string const&>(var));
return 0;
}
在以上两个 var
用法的版本中,不会传递给字符串函数.我尝试了其他各种方法来指定参数,但似乎没有办法: std :: string&&值
, std :: string const&值
, std :: string const&&值
.我也确实尝试过 std :: string&值
,然后匹配非常量字符串,但不匹配常量字符串.通过提供两个不同的功能,这至少为我提供了一种解决方法,但是我怀疑我不需要这样做.
In the version above the two var
uses do not get passed to the string function. I have tried various other ways of specifying the parameter but none seem to do the trick: std::string && value
, std::string const & value
, std::string const && value
. I did also try just std::string & value
and then the non-const strings match, but not the const ones. This provides me with at least a workaround by having two different functions, but I suspect I shouldn't need to do this.
如何在此处编写一个将为const,非const和临时字符串对象调用的函数?
How do I write a single function here that will be called for const, non-const, and temporary string objects?
我正在使用g ++ 4.6.3
推荐答案
我重新研究了这个问题,并提出了一个涉及使用类标记的解决方案.我写了一篇完整解决方案/讨论的文章.
I revisited the problem and came up with a solution which involves using a class marker. I've written an article with the full solution/discussion.
这篇关于可变参数模板麻烦匹配const和非const std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!