簡體   English   中英

C++ 朋友 function 與模板參數 enable_if

[英]C++ friend function with a template argument enable_if

我正在與朋友 function 為一個帶有enable_if模板參數的結構而苦苦掙扎:

// foo.h
#ifndef FOO_H
#define FOO_H
#include <type_traits>

template<
    typename T,
    typename = typename std::enable_if<std::is_arithmetic<T>::value>::type
>
struct foo {
    foo(T bar) : bar(bar) {}

    T get() { return bar; }

    friend foo operator+(const foo& lhs, const foo& rhs);
    // Defining inside a body works:
    // {
    //     return foo(lhs.bar + rhs.bar);
    // }

private:
    T bar;
};

// None of these work:
// tempate<typename T, typename>
// tempate<typename T>
// tempate<typename T, typename = void>
template<
    typename T,
    typename = typename std::enable_if<std::is_arithmetic<T>::value>::type
>
foo<T> operator+(const foo<T>& lhs, const foo<T>& rhs)
{
    return foo<T>(lhs.bar + rhs.bar);
}
#endif /* ifndef FOO_H */

// main.cpp
#include <iostream>
#include "foo.h"

int main()
{
    foo<int> f{1};
    foo<int> g{2};
    std::cout << (f + g).get() << '\n';
    return 0;
}

如果我嘗試編譯,得到以下 linker 錯誤:

Undefined symbols for architecture x86_64:
  "operator+(foo<int, void> const&, foo<int, void> const&)", referenced from:
      _main in main-5fd87c.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

(使用Apple clang version 11.0.3 (clang-1103.0.32.59) 。)

我希望運算符 + 僅適用於具有相同模板 arguments 的類型,例如,foo 僅適用於 foo,而不適用於 foo 或 foo。

我認為這與這個問題密切相關,但我很難弄清楚如何解決我的問題。 我嘗試了許多模板定義,例如tempate<typename T, typename>tempate<typename T>tempate<typename T, typename = typename std::enable_if...>但這些都不起作用。

如代碼中所述,在主體內部定義是可行的,但我想學習如何使用具有類型特征的模板友元函數。 任何幫助將不勝感激!

朋友聲明是指非模板運算符,而 class 定義中的定義是指模板之一,它們不匹配。

你可能想要

// forward declaration of the class template
template<
    typename T,
    typename X = typename std::enable_if<std::is_arithmetic<T>::value>::type
>
struct foo;

// declaration of the operator template
template<
    typename T,
    typename = typename std::enable_if<std::is_arithmetic<T>::value>::type
>
foo<T> operator+(const foo<T>& lhs, const foo<T>& rhs);

// definition of the class template
template<
    typename T,
    typename
>
struct foo {
    foo(T bar) : bar(bar) {}

    T get() { return bar; }

    friend foo operator+<T>(const foo& lhs, const foo& rhs);
    // or left the template parameters to be deduced as
    friend foo operator+<>(const foo& lhs, const foo& rhs);

private:
    T bar;
};

//definition of the operator template
template<
    typename T,
    typename
>
foo<T> operator+(const foo<T>& lhs, const foo<T>& rhs)
{
    return foo<T>(lhs.bar + rhs.bar);
}

居住

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM