C ++模板参数默认函数实现

时间:2016-01-14 18:34:03

标签: c++ templates c++-concepts

我有一组用作模板参数的类。 它们都符合一些非正式的界面(a.k.a。概念)

template <typename T>
int func( T& t ) { return t.a() + t.b() + t.c(); }

在此示例中,我说我使用FooBar作为参数来实例化模板,因此他们必须实现方法a b和{{1 }}

c

现在,我有很多这样的类,我希望其中一个函数的默认实现。

例如,我希望struct Foo { int a(); int b(); int c(); }; struct Bar { int a(); int b(); int c(); }; 默认返回ca()之间的差异。所以我希望我定义b()a()以及b()自动实现为c()就足够了,而不必为所有类复制此​​代码。

我曾经用多态来实现这个结果(通过将int c() { return a()- b();}a()定义为基类中的纯虚函数,默认(虚拟)实现b()),但我出于性能原因,他们离开了这个机制。

我想知道是否有推荐的解决方案来获得这种结果(即使用我的模板参数类编写一次默认实现)。

4 个答案:

答案 0 :(得分:9)

我很想从std::begin偷一页。

CRTP很棒,但它要求每个结构都修改自己来处理你对c的要求。实际上,c的代码是你的问题,而不是你被喂的数据的问题。

当然,你需要零开销,CRTP和这种方法都可以实现。

相反,我们有条件地调用.c()或我们根据其存在调用.a()+.b()。这有两种方法:

创建免费功能c

template<class T, class...Ignored>
decltype(auto) c(T& t, Ignored&&...)

它发送给两个实现:

{
  auto which = has_c_method<T>;
  return details::c(which{}, t);
}

其中has_c_method是特征bool类型,用于检测传递的类型是否具有.c()方法。 (我在下面写一个。)

在命名空间详细信息中:

namespace details{
  template<class T>
  auto c(std::false_type, T&){
    return t.a()-t.b();
  }
  template<class T>
  auto c(std::true_type, T&){
    return t.c();
  }
}

我们很好。另请注意,如果c(t)命名空间中存在免费的非变量函数t,则会优先考虑(这是Ignored所做的事情。)

你必须写那个特质类,但很多SO答案都涵盖了这一点。

建议使用比c更好的名称。 ;)

此设计的优点是不会强迫人们编写目标类型以参与操作。您只需访问t.c()t.a()+t.b(),具体取决于是否定义t.c()

现在我们可以从一个更通用的方向来解决这个问题。我们不创建为我们发送的c函数,而是......

我们编写一个编译时分支:

namespace details {
  template<bool>
  struct branch {
    template<class T, class F_true, class F_false>
    std::result_of_t<F_true(T)> operator()( T&&t, F_true&&f, F_false&&){
      return decltype(f)(f)(decltype(t)(t));
    }
  };
  template<>
  struct branch<false> {
    template<class T, class F_true, class F_false>
    std::result_of_t<F_false(T)> branch( T&& t, F_true&&, F_false&&f){
      return decltype(f)(f)(decltype(t)(t));
    }
  };
}
template<template<class...>class Z, class T, class F_true, class F_false>
auto branch( T&& t, F_true&& f_true, F_false&& f_false )
-> decltype( details::branch<Z<T>{}>{}(std::declval<T>(), std::declval<F_true>(), std::declval<F_false>() )
{
  return details::branch<Z<T>{}>{}(decltype(t)(t), decltype(f_true)(f_true), decltype(f_false)(f_false) );
}

没有虚假的情况:

template<template<class...>class Z, class T, class F_true>
void branch( T&& t, F_true&& f_true )
{
  branch( std::forward<T>(t), std::forward<F_true>(f_true), [](auto&&){} );
}

使用:

int c = branch<has_c_method>(
  t,
  [&](auto& t){ return t.c(); },
  [&](auto& t){ return t.a()-t.b(); }
);

可以让你更专注地做这件事。

branch<template>( arg, if_true, if_false )评估template类型(包括r / l值限定)arg。如果结果类型的实例在constexpr上下文中返回true,则运行if_true。如果在constexpr竞赛中返回false,则运行if_false

在这两种情况下,arg都会传递给选定的lambda。

与来自C ++ 14的auto lambda支持一起,这使您可以编写有条件编译的相对简洁的代码。

unrun lambda只是一个未实例化的模板。运行lambda使用arg实例进行实例化。因此,未运行的lambda不需要包含未选择它的情况下的有效代码。

branch的类型实际上是在两个选项之间静态选择的;他们实际上可以返回不同类型。没有转换。

branch的if_false-less重载返回void,因为我很懒,而且看不太有用。

以下是has_c_method的草图,主要是通用代码。

namespace details {
  template<template<class...>class Z, class, class...Ts>
  struct can_apply_helper:
    std::false_type
  {};
  template<template<class...>class Z, class...Ts>
  struct can_apply_helper<Z, std::void_t<Z<Ts...>>, Ts...>:
    std::true_type
  {};
}
// is true_type iff Z<Ts...> is valid:
template<template<class...>class Z, class...Ts>
using can_apply = typename details::can_apply_helper<Z, void, Ts...>::type;

// return type of t.c(args...).  Easy to write
// and with the above, makes has_c_method a one-liner:
template<class T, class...Args>
using c_method_result = decltype(std::declval<T>().c(std::declval<Args>()...));

template<class T, class...Args>
using has_c_method = can_apply<c_method_result, T, Args...>;

有人建议将can_apply添加到std

请注意我上面decltype(x)(x)的非惯用用法。这相当于std::forward<X>(x)X是转发引用的上下文中的auto&&,并且也适用于x参数lambdas。这意味着“将x转换为声明它的类型”。请注意,如果decltype(x)(x)是一个值(非引用)类型,它将重复它(这是偏向前的原因,从不这样做):但是,这不是以上任何body使用的情况。

答案 1 :(得分:2)

如何使用CRTP为从其继承的类提供默认实现:

template <typename Child>
class DefaultC
{
public:
    int c() { Child& this_obj = static_cast<Child&>(*this); return this_obj.a()- this_obj.b();}
};

然后:

struct Foo : public DefaultC<Foo> { int a(); int b(); };

(并注意如果你的函数是非变异的,请将它们标记为const)

答案 2 :(得分:2)

我首先尝试CRTP:

template < typename Derived >
struct subtract
{
    int c() const
    {
        auto this_ = static_cast<Derived const*>(this);
        return this_->a() - this_->b();
    }
};

struct whatnot : subtract<whatnot>
{
    int a() const { return 42; }
    int b() const { return 666; }
};

答案 3 :(得分:2)

一个版本,受到Kerrek评论的启发,但使用std::true_typestd::false_type

#include <iostream>
#include <type_traits>

struct Foo {
    int a() { return 10; }
    int b() { return 20; }
    int c() { return 30; }
};

struct Bar {
    int a() { return 8; }
    int b() { return 3; }
};

template<typename T, typename = void>
struct has_c : std::false_type {
    static int call(T t) { return t.a() - t.b(); }
};

template<typename T>
struct has_c<T, decltype(std::declval<T>().c(), void())> : std::true_type {
    static int call(T t) { return t.c(); }    
};

template <typename T>
int f(T&& t) {
    return has_c<T>::call(std::forward<T>(t));
}

int main()
{
    Foo foo;
    Bar bar;

    std::cout << f(foo) << "\n";
    std::cout << f(bar) << "\n";

    return 0;
}

Live on Coliru

相关问题