推导基类的函数模板参数

时间:2018-09-20 15:56:13

标签: c++ template-meta-programming

在此示例中,我只需要实例化基类类型的模板函数。

struct A{ int i=0; };
struct A1:A{};
struct A2:A{};

struct B{ int i=1; };
struct B1:B{};
struct B2:B{};

template<typename T> uint32_t Checksum ( const T& t )
{
    // make sure we are not instantiating redundant functions
    static_assert(std::is_same<T,A>::value || std::is_same<T,B>::value,"");

    return t.i;
}
template uint32_t Checksum ( const A& t ); //this are actually no ops
template uint32_t Checksum ( const B& t ); //this are actually no ops

int main()
{
    A1 a1;
    A2 a2;
    B1 b1;
    B2 b2;
    Checksum<A>(a1);//ok
    Checksum<A>(a2);//ok
    Checksum<B>(b1);//ok
    Checksum<B>(b2);//ok
    Checksum(b2);  //error

    return 0;
}

是否可以强制将模板类型推论推向基类,理想情况下无需C ++ 17推论指南,这样我就不必在调用时指定类型?

我也试图显式实例化这些函数,想知道它们最终是否会在函数重载解析中起作用,但是编译器没有选择它们。也许这可能有一些窍门。

1 个答案:

答案 0 :(得分:0)

怎么样:

foo.h

struct A{ int i=0; };
struct A1:A{};
struct A2:A{};

struct B{ int i=1; };
struct B1:B{};
struct B2:B{};

uint32_t Checksum ( const A& t );
uint32_t Checksum ( const B& t );

checkSum.cpp

#include "foo.h"

template<typename T> uint32_t ChecksumImpl ( const T& t )
{
    // make sure we are not instantiating redundant functions
    static_assert(std::is_same<T,A>::value || std::is_same<T,B>::value,"");

    return t.i;
}
uint32_t Checksum ( const A& t ) { return ChecksumImpl (t);}
uint32_t Checksum ( const B& t ) { return ChecksumImpl (t);}

main.cpp

#include "foo.h"

int main()
{
    A1 a1;
    A2 a2;
    B1 b1;
    B2 b2;
    Checksum(a1);//ok
    Checksum(a2);//ok
    Checksum(b1);//ok
    Checksum(b2);//ok
}