c++ - 使用 auto->decltype 方法显式实例化函数

标签 c++ templates explicit-instantiation

我想创建能够提取结构 A 的任何属性的模板函数。

这是Source.h

struct B
{
    int bbb;
};

struct C
{
    double ccc;
};

struct A
{
    B b;
    C c;
};

template <class R>
auto foo(A* str, R getter) -> decltype(str->*getter);

现在我想对 foo 使用显式实例化方法

Source.cpp 来了:

#include "Source.h"

template <class R>
auto foo(A* str, R getter) -> decltype(str->*getter)
{
    return str->*getter;
}

如果我们查看 Main.cpp,我们可以看到,如果没有在上面的代码块中显式实例化,我们会得到链接错误:

//MAIN.cpp
#include "Source.h"

void main()
{
    A a;
    a.b.bbb = 7;
    auto z = foo(&a, &A::b);
}

现在我的问题是如何为 &A::b 和 &A::c 类型显式实例化 foo。 我尝试了很多变体,但没有任何效果。我在 visual studio 2015 中。

附言哦,还有一个。我们可以用默认参数制作 foo 吗? R = decltype(&A::b) ?

最佳答案

你去吧:

template B &foo(A*, B A::*);
template C &foo(A*, C A::*);

至于默认参数,你需要类型和值的默认值:

template <class R = B A::*>
auto foo(A* str, R getter = &A::b) -> decltype(str->*getter);

关于c++ - 使用 auto->decltype 方法显式实例化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48326974/

相关文章:

c++ - 如何构建模板的显式实例化以提高编译速度?

c++ - 显式实例化可变参数构造函数 : template-id does not match any template declaration

c++ - if( var == 'x' ) 这样的语句中的文字存储在哪里?

c++ - 由于 recvfrom 函数阻塞程序执行导致程序卡住

c++ - 填充可变大小数组

c++ - GCC 向依赖默认构造函数的模板化类中的静态数据成员给出 "undefined reference"错误

c++ - C++17 模板中的可选运算符重载

c++ - 专用模板的多重实例化

c++ - 递归函数有 out_of_range 异常

c++ - 具有基于身份的相等性的有序关联容器