小编SNJ*_*SNJ的帖子

模板或成员函数选择

我一直试图了解 C++ 选择模板或成员函数的方式。考虑以下代码示例:

#include <iostream>
#include <string>

struct Test
{
    template<typename X>
    explicit Test( X&& s){ std::cout << "1" << std::endl;}
    
    explicit Test( const std::string& s) { std::cout << "2"<< std::endl; }
    explicit Test( std::string&& s) { std::cout << "3"<<  std::endl; }

};

int main ()
{
    std::string line = "TEST";
    Test test( line );
}
Run Code Online (Sandbox Code Playgroud)

我在控制台上打印了“1”。如果是与参数类型匹配的非模板,为什么不选择“2”?

c++ templates

6
推荐指数
1
解决办法
70
查看次数

C++ 类型特征来检测是否有任何函数参数是引用

我需要一个类型特征来检测模板参数的任何函数参数是否是引用。这段代码正在工作,特征是“is_any_param_reference”,并且 static_assert 被触发,foo 的签名更改void foo( std::string s, int i)void foo( std::string& s, int i)(第一个参数转换为引用)。

但 id 不能与 lambda 一起使用...如果我使用它则无法编译:

int main()
{ 
    auto foo2 = [](std::string s, int i){ std::cout << s << " " << i << std::endl; };
    some_function( foo2, s, i  );
}
Run Code Online (Sandbox Code Playgroud)

知道如何生成也适用于 lambda 的类型特征吗?

谢谢!!

#include <iostream>
#include <string>
#include <type_traits>

using namespace std;

template<typename ... A>
struct any_is_reference : std::false_type {};
template<typename A, typename ... P>
struct any_is_reference<A, P...>: std::conditional_t< …
Run Code Online (Sandbox Code Playgroud)

c++ lambda templates type-traits c++11

4
推荐指数
1
解决办法
872
查看次数

标签 统计

c++ ×2

templates ×2

c++11 ×1

lambda ×1

type-traits ×1