簡體   English   中英

使用-Waddress時在C ++ 14中檢查功能模板的有效性

[英]Check function template validity in C++14 when using -Waddress

使用-Waddress編譯此代碼時:

#include <iostream>
#include <memory>
#include <string.h>

template <typename T, void (*func)(T*) = nullptr>
struct Caller {
    Caller(T* ptr = nullptr)
    {
        std::cout
            << "Creating caller " << ptr
            << ", is function " << std::is_function<decltype(func)>()
            << ", is null " << std::is_null_pointer<decltype(func)>()
            << ", function is " << func
            << std::endl;

        if (func)
        {
            std::cout << "Running for " << ptr << " func " << func << std::endl;
            func(ptr);
        }
    }
};

void free_char(char *c) { free(c); }

int main() {
    Caller<char, free_char>(strdup("Test"));
    Caller<const char>("Test2");
    return 0;
}

它將失敗並顯示:

/tmp/foo.cpp: In instantiation of ‘Caller<T, func>::Caller(T*) [with T = char; void (* func)(T*) = free_char]’:
/tmp/foo.cpp:36:40:   required from here
/tmp/foo.cpp:13:33: warning: the address of ‘void free_char(char*)’ will never be NULL [-Waddress]

解決方法是使用類似if (auto f = func) f(ptr); 但我想在編譯時進行靜態檢查。

該解決方案提到了模板專業化的用法,但是在這里,我們要處理一個結構,這是我想使用靜態模板檢查的一種情況。

如何在默認情況下簡單地提供無操作功能而不是空指針呢? 這樣就完全擺脫了if局面,使代碼更簡潔。

template<typename T>
void no_op(T*) {}

template <typename T, void (*func)(T*) = no_op<T>>
struct Caller {
    static_assert(func != nullptr, "don't pass nullptr");
    Caller(T* ptr = nullptr)
    {
        std::cout
            << "Creating caller " << ptr
            << ", is function " << std::is_function<decltype(func)>()
            << ", is null " << std::is_null_pointer<decltype(func)>()
            << ", function is " << func
            << std::endl;

        std::cout << "Running for " << ptr << " func " << func << std::endl;
        func(ptr);
    }
};

暫無
暫無

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

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