小编Jaa*_*aan的帖子

Template deduction depends on another template deduction

Since std::format isn't supported everywhere, and I didn't want another large dependency like fmt, I wanted to quickly roll my own to_string solution for a number of types. The following is the code.

#include <ranges>
#include <string>
#include <concepts>

template<typename Type>
constexpr std::string stringify(const Type &data) noexcept;

template<typename Type> requires std::integral<Type>
constexpr std::string stringify(const Type &data) noexcept {
    return std::to_string(data);
}

template<typename Type>
constexpr std::string stringify_inner(const Type &data) noexcept {
    return stringify(data);
}

template<typename Type> requires std::ranges::range<Type>
constexpr std::string …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm templates c++20 function-templates-overloading

5
推荐指数
1
解决办法
182
查看次数

实例彼此独立的唯一类型的计数器

我试图为计数器接收到的每个唯一模板参数创建一个计数器。

例如,我传递一个 int。计数器返回零。我经过一个花车。计数器返回 1。我再次传递一个 int 。计数器返回零。本质上,它为每个模板化类型生成一个唯一的整数。

struct Counter {
    template<typename T>
    int type();
    int tick();
};

template<typename T>
int Counter::type() {
    static int index = tick();
    return index;
}

int Counter::tick() {
    static int index = 0;
    return index++;
}

int main() {
    Counter countera;
    Counter counterb;

    std::cout << countera.type<int>() << std::endl;
    std::cout << countera.type<float>() << std::endl;
    std::cout << countera.type<double>() << std::endl;

    std::cout << counterb.type<float>() << std::endl;
    std::cout << counterb.type<int>() << std::endl;
    std::cout << counterb.type<double>() << std::endl;

    return 0;
} …
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
166
查看次数

为什么这个映射返回右值?

我正在使用库nlohmann/json并希望创建一个unordered_mapof std::stringto nlohmann::json

#include <nlohmann/json.hpp>

class basic_container {
public:
    using key_type = std::string;
    using mapped_type = nlohmann::json;
    using container_type = std::unordered_map<key_type, mapped_type>;
    using reference = typename container_type::reference;
    using const_reference = typename container_type::const_reference;

    // error: cannot bind non-const lvalue reference to an rvalue
    reference at(const key_type &key) {
        return data.at(key);
    }

    // warning: returning reference to temporary
    const_reference at(const key_type &key) const {
        return data.at(key);
    }

    // error: cannot bind non-const lvalue reference to an …
Run Code Online (Sandbox Code Playgroud)

c++ nlohmann-json

1
推荐指数
1
解决办法
176
查看次数