簡體   English   中英

使用模板 C++ 進行類型測試

[英]Type testing with templates C++

所以我有一個函數,它采用兩種可能的參數類型,每一種都是我預定義的 lambda 函數類型。 兩種可能性是 CellFType 和 FType。 兩種情況下的函數幾乎相同,但在一行中,我需要它根據 FunctionType 執行兩種不同的操作。 我想避免為此造成額外的重載,因此我將其模板化

/// Returns the integral 2 norm of a function

template <typename FunctionType>
double norm(const FunctionType &f)
{
    double value = 0.0;

    for (size_t iT = 0; iT < n_cells; iT++)
    {
        QuadratureRule quadT = cell_quads[iT];
        for (size_t iqn = 0; iqn < quadT.size(); iqn++)
        {
            double qr_weight = quadT[iqn].w;

            VectorRd f_on_qr = (typeid(FunctionType) == typeid(FType<VectorRd>) ? 
            f(quadT[iqn].vector()) : f(quadT[iqn].vector(), cells[iT])); // *ERROR*

            value += qr_weight * scalar_product(f_on_qr, f_on_qr);
        }
    }

    return sqrt(value);
}

FType 和 CellFType 也都是這樣模板化的:

template <typename T>
using CellFType = std::function<T(const VectorRd &, const Cell *)>;

template <typename T>
using FType = std::function<T(const VectorRd &)>;

為什么這會導致問題? 如何在此處正確鍵入測試?

注釋中的解決方案,調用重載函數,當然是最容易理解的,因此也是最好的方法。

但是,有時最好將其全部內聯。 由於您使用的是 C++17,因此有一個與std::visit一起使用的輔助類:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;  

它需要一堆 lambda 表達式,並將它們轉換為一個帶有調用運算符重載的類來調用每個 lambda。 您也可以使用它來發送您的案例:

VectorRd f_on_qr = overloaded {
    [&](FType<VectorRd> g) { return g(quadT[iqn].vector()); },
    [&](CellFType<VectorRd> g) { return g(quadT[iqn].vector(), cells[iT])); }
} (f);

概念證明: https : //godbolt.org/z/G5qWGK

暫無
暫無

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

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